import blue
import xtriui
import uix
import form
import uthread
import uiutil
import uiconst
import uicls
from service import ROLE_GML
COLOURTABLE = {1: 10,
 0: -10}

class TournamentWindow(uicls.Window):
    __guid__ = 'form.tournament'
    __neocommenuitem__ = (('Tournament Manager', 'tournament'),
     True,
     ROLE_GML)
    mouseOver = {'tournamentVOffset': 'Determines the vertical offset of the icons',
     'tournamentHOffset': 'Determines the horizontal offset of the icons',
     'tournamentSpacing': 'Determines the vertical spacing between icons'}

    def ApplyAttributes(self, attributes):
        uicls.Window.ApplyAttributes(self, attributes)
        self.height = 180
        self.width = 400
        self.buttonHeight = 30
        self.tabHeight = 18
        self.panelHeight = ((self.height - self.buttonHeight) - self.tabHeight)
        self.SetScope('all')
        self.SetWndIcon(None)
        self.SetCaption('Tournament Manager')
        self.SetTopparentHeight(0)
        self.SetMinSize([self.width, self.height])
        self.MakeUnResizeable()
        self.ConstructLayout()
        self.LoadOptions()



    def ConstructLayout(self):
        tabParent = uicls.Container(name='tabparent', parent=self.sr.main, align=uiconst.TOTOP, pos=(0,
         0,
         0,
         self.tabHeight))
        teamOptions = uicls.Container(name='teamOptions', parent=self.sr.main, align=uiconst.TOTOP, pos=(const.defaultPadding,
         0,
         const.defaultPadding,
         self.panelHeight), padding=(0, 0, 0, 0))
        settingOptions = uicls.Container(name='settingOptions', parent=self.sr.main, align=uiconst.TOTOP, pos=(const.defaultPadding,
         0,
         const.defaultPadding,
         self.panelHeight), padding=(0,
         0,
         (const.defaultPadding * 2),
         0))
        debugOptions = uicls.Container(name='debugOptions', parent=self.sr.main, align=uiconst.TOTOP, pos=(const.defaultPadding,
         0,
         const.defaultPadding,
         self.panelHeight), padding=(0,
         0,
         (const.defaultPadding * 2),
         0))
        btnParent = uicls.Container(name='btnparent', parent=self.sr.main, align=uiconst.TOBOTTOM, pos=(0,
         0,
         0,
         self.buttonHeight))
        tabs = [['Teams',
          teamOptions,
          self.sr.main,
          'teams'],
         ['Settings',
          settingOptions,
          self.sr.main,
          'settings'],
         ['Debug',
          debugOptions,
          self.sr.main,
          'debug']]
        self.sr.tabs = form.TabGroup(uicls.Container(name='tabsubparent', parent=tabParent, align=uiconst.TOTOP, pos=(const.defaultPadding,
         0,
         0,
         0)))
        self.sr.tabs.Startup(tabs, 'tabs')
        btns = [['Toggle',
          self.DoViewToggle,
          None,
          81],
         ['Align',
          self.DoTargetAlign,
          None,
          81],
         ['Sort',
          self.DoTargetSort,
          None,
          81],
         ['Lock',
          self.DoLockGrid,
          None,
          81],
         ['Unlock',
          self.DoUnlockAll,
          None,
          81],
         ['Hide',
          self.DoHideWnd,
          None,
          81]]
        uix.MakeBtnGroup(btns, where=btnParent, uniSize=0)
        cmbWidth = 75
        self.sr.filter = uicls.Combo(label='Filter', labelleft=cmbWidth, parent=teamOptions, align=uiconst.TOTOP, name='tournamentFilter', options=None, pos=(0,
         const.defaultPadding,
         0,
         0), callback=self.FilterChange)
        self.sr.filter.padLeft = (cmbWidth + const.defaultPadding)
        self.sr.filter.padRight = const.defaultPadding
        self.sr.primarySortField = uicls.Combo(label='Sort [pri]', labelleft=cmbWidth, parent=teamOptions, align=uiconst.TOTOP, name='tournamentPriSort', options=None, pos=(0,
         const.defaultPadding,
         0,
         0), callback=self.FilterChange)
        self.sr.primarySortField.padLeft = (cmbWidth + const.defaultPadding)
        self.sr.primarySortField.padRight = const.defaultPadding
        self.sr.secondarySortField = uicls.Combo(label='Sort [sec]', labelleft=cmbWidth, parent=teamOptions, align=uiconst.TOTOP, name='tournamentSecSort', options=None, pos=(0,
         const.defaultPadding,
         0,
         0), callback=self.FilterChange)
        self.sr.secondarySortField.padLeft = (cmbWidth + const.defaultPadding)
        self.sr.secondarySortField.padRight = const.defaultPadding
        self.sr.teamBeta = uicls.Combo(label='Left [red]', labelleft=cmbWidth, parent=teamOptions, align=uiconst.TOTOP, name='beta', options=None, pos=(0,
         const.defaultPadding,
         0,
         0), callback=self.TeamSet)
        self.sr.teamBeta.padLeft = (cmbWidth + const.defaultPadding)
        self.sr.teamBeta.padRight = const.defaultPadding
        self.sr.teamAlpha = uicls.Combo(label='Right [blue]', labelleft=cmbWidth, parent=teamOptions, align=uiconst.TOTOP, name='alpha', options=None, pos=(0,
         const.defaultPadding,
         0,
         0), callback=self.TeamSet)
        self.sr.teamAlpha.padLeft = (cmbWidth + const.defaultPadding)
        self.sr.teamAlpha.padRight = const.defaultPadding
        alignmentSub = uicls.Container(name='alignmentFrame', parent=settingOptions, align=uiconst.TOTOP, pos=(const.defaultPadding,
         const.defaultPadding,
         0,
         18))
        txt = uicls.Label(text='Alignment:', name='align', parent=alignmentSub, align=uiconst.TOLEFT, height=13, top=const.defaultPadding, left=const.defaultPadding, autoheight=False, fontsize=10, letterspace=1, linespace=9, uppercase=1, state=uiconst.UI_NORMAL)
        txt.rectTop = -3
        self.sr.voffset = uicls.SinglelineEdit(name='tournamentVOffset', parent=alignmentSub, setvalue=prefs.GetValue('tournamentVOffset', 10), left=const.defaultPadding, width=50, height=20, align=uiconst.TORIGHT, ints=(-100, 100))
        self.sr.voffset.OnReturn = self.OnEnterVOffset
        self.sr.voffset.OnFocusLost = self.SetPrefsValue
        self.sr.voffset.hint = self.mouseOver[self.sr.voffset.name]
        txt = uicls.Label(text='V-Offset', name='offsetText', parent=alignmentSub, align=uiconst.TORIGHT, height=13, top=const.defaultPadding, left=const.defaultPadding, autoheight=False, fontsize=10, letterspace=1, linespace=9, uppercase=1, state=uiconst.UI_NORMAL)
        txt.rectTop = -3
        txt.hint = self.mouseOver[self.sr.voffset.name]
        self.sr.hoffset = uicls.SinglelineEdit(name='tournamentHOffset', parent=alignmentSub, setvalue=prefs.GetValue('tournamentHOffset', 10), left=10, width=50, height=20, align=uiconst.TORIGHT, ints=(-100, 100))
        self.sr.hoffset.OnReturn = self.OnEnterHOffset
        self.sr.hoffset.OnFocusLost = self.SetPrefsValue
        self.sr.hoffset.hint = self.mouseOver[self.sr.hoffset.name]
        txt = uicls.Label(text='H-Offset', name='horizText', parent=alignmentSub, align=uiconst.TORIGHT, height=13, top=const.defaultPadding, left=const.defaultPadding, autoheight=False, fontsize=10, letterspace=1, linespace=9, uppercase=1, state=uiconst.UI_NORMAL)
        txt.rectTop = -3
        txt.hint = self.mouseOver[self.sr.hoffset.name]
        self.sr.spacing = uicls.SinglelineEdit(name='tournamentSpacing', parent=alignmentSub, setvalue=prefs.GetValue('tournamentSpacing', 10), left=10, width=50, height=20, align=uiconst.TORIGHT, ints=(-100, 100))
        self.sr.spacing.OnReturn = self.OnEnterSpacing
        self.sr.spacing.OnFocusLost = self.SetPrefsValue
        self.sr.spacing.hint = self.mouseOver[self.sr.spacing.name]
        txt = uicls.Label(text='V-Spacing', name='vertText', parent=alignmentSub, align=uiconst.TORIGHT, height=13, top=const.defaultPadding, left=const.defaultPadding, autoheight=False, fontsize=10, letterspace=1, linespace=9, uppercase=1, state=uiconst.UI_NORMAL)
        txt.rectTop = -3
        txt.hint = self.mouseOver[self.sr.spacing.name]
        self.sr.changeSprite = uicls.AnimSprite(blue.os.LoadObject('res:/UI/Component/loadingindicator.blue'))
        self.sr.changeSprite.anchors = uix.UI_ANCHRIGHT
        self.sr.changeTimer = uicls.Container(name='changeTimer', parent=teamOptions, pos=(const.defaultPadding,
         -106,
         320,
         0))
        self.sr.changeTimer.children.append(self.sr.changeSprite)
        self.sr.changeSprite.Startup(18, 208, 16, 16, 8)
        self.sr.changeSprite.state = uix.UI_HIDDEN
        debugbtnParent = uicls.Container(name='debugbtnParent', parent=debugOptions, align=uiconst.TOTOP, pos=(const.defaultPadding,
         const.defaultPadding,
         0,
         30))
        debugbtns = [['Swap Sides',
          self.SwapTeams,
          None,
          81]]
        uix.MakeBtnGroup(debugbtns, where=debugbtnParent, uniSize=0, line=0)



    def LoadOptions(self):
        filterOptions = [('Alliance', 'allianceID'),
         ('Militia', 'warFactionID'),
         ('Corporation', 'corpID')]
        self.sr.filter.entries = filterOptions
        value = prefs.GetValue('tournamentFilter', 'allianceID')
        self.sr.filter.SetValue(value)
        sortOptions = [('Radius', const.attributeSignatureRadius),
         ('Mass', const.attributeMass),
         ('Volume', const.attributeVolume),
         ('Race', const.attributeRaceID),
         ('Tech Level', const.attributeTechLevel),
         ('Meta Level', const.attributeMetaLevel),
         ('Meta Group', 'parent'),
         ('Group ID', 'group')]
        sortingPrecedence = [(self.sr.primarySortField,
          const.attributeRaceID,
          'tournamentPriSort'), (self.sr.secondarySortField,
          'parent',
          'tournamentSecSort')]
        for (sortingCombo, default, prefsName,) in sortingPrecedence:
            sortingCombo.entries = sortOptions
            value = prefs.GetValue(prefsName, default)
            sortingCombo.SetValue(value)

        uthread.new(self.SetTeamFilter, self.sr.filter.GetValue())



    def FilterChange(self, combo, text, value, *args):
        prefs.SetValue(combo.name, value)
        if (combo.name in ('tournamentFilter',)):
            uthread.new(self.SetTeamFilter, value)



    def SetTeamFilter(self, field):
        if (field is None):
            return 
        self.sr.changeSprite.Play()
        for combo in (self.sr.teamAlpha, self.sr.teamBeta):
            entries = self.GetFilteredUsersInLocal(field)
            if not entries:
                entries = [(u'No choices', None)]
            entries.sort()
            combo.entries = entries
            combo.SetValue(entries[0][1])

        self.sr.changeSprite.Stop()



    def TeamSet(self, combo, text, value, *args):
        opposingTeam = {'alpha': 'teamBeta',
         'beta': 'teamAlpha'}
        if (value == getattr(self.sr, opposingTeam[combo.name]).GetValue()):
            eve.Message('CustomNotify', {'notify': 'You have set the same team for both sides.'})



    def SetPrefsValue(self, singleLineEdit):
        if (hasattr(singleLineEdit, '__guid__') and (singleLineEdit.__guid__ == 'xtriui.SingleLineEdit')):
            prefs.SetValue(singleLineEdit.name, int(singleLineEdit.GetValue()))
            sm.GetService('target').ArrangeTargets()



    def _OnEnterOffset(self, fieldObject):
        self.SetPrefsValue(fieldObject)



    def OnEnterVOffset(self):
        self._OnEnterOffset(self.sr.voffset)



    def OnEnterHOffset(self):
        self._OnEnterOffset(self.sr.hoffset)



    def OnEnterSpacing(self):
        self.SetPrefsValue(self.sr.spacing)



    def GetFilteredUsersInLocal(self, filterValue):
        local = (('solarsystemid2', session.solarsystemid2))
        channel = sm.GetService('LSC').GetChannelWindow(local)
        userList = channel.userlist.sr.entries
        filtered = set()
        for user in userList:
            value = getattr(user, filterValue)
            if (value is not None):
                filtered.add(value)

        return map(self.GetNameFromID, list(filtered))



    def GetNameFromID(self, objectID):
        name = cfg.eveowners.Get(objectID).ownerName
        filterValue = self.sr.filter.GetValue()
        if (filterValue in ('allianceID', 'corpID')):
            lookup = {'allianceID': 'allianceshortnames',
             'corpID': 'corptickernames'}
            name += (' [%s]' % getattr(cfg, lookup[filterValue]).Get(objectID).name)
        return (name, objectID)



    def DoViewToggle(self, *args):
        try:
            standings = {}
            if sm.GetService('target').IsObserving():
                bp = sm.GetService('michelle').GetBallpark()
                for itemID in sm.GetService('target').GetTargets():
                    slim = bp.GetInvItem(itemID)
                    if not hasattr(slim, 'corpID'):
                        continue
                    standings[slim.corpID] = 0

                self.DoSetColour(standings)

        finally:
            sm.GetService('target').ToggleViewMode()
            wnd = sm.GetService('window').GetWindow('tournament', create=0)
            if wnd:
                wnd.Maximize()




    def DoTargetAlign(self, *args):
        alignTable = {self.sr.teamAlpha.GetValue(): 1,
         self.sr.teamBeta.GetValue(): 0}
        teamFilter = self.sr.filter.GetValue()
        bp = sm.GetService('michelle').GetBallpark()
        if ((bp is None) or (session.stationid is not None)):
            eve.Message('CustomNotify', {'notify': 'You must be in space for this to work.'})
            return 
        standings = {}
        for itemID in sm.GetService('target').GetTargets():
            slim = bp.GetInvItem(itemID)
            team = sm.GetService('target').GetTeam(itemID)
            if (getattr(slim, teamFilter) in alignTable):
                alignValue = alignTable[getattr(slim, teamFilter)]
                if not hasattr(slim, 'corpID'):
                    pass
            standings[slim.corpID] = COLOURTABLE[alignValue]
            if (alignValue != team):
                sm.GetService('target').ToggleTeam(itemID)
            else:
                continue

        self.DoSetColour(standings)



    def DoSetColour(self, standings):
        who = set(standings.keys())
        for corpID in who:
            standing = standings[corpID]
            if (standing == 0):
                self.DoReset(corpID)
            else:
                self._TournamentWindow__DoSetColour(corpID, standing)




    def __DoSetColour(self, who, colour, *args):
        return 



    def DoReset(self, toID):
        return 



    def DoTargetSort(self, *args):
        tg = sm.GetService('target')
        bp = sm.GetService('michelle').GetBallpark()
        if ((bp is None) or (session.stationid is not None)):
            eve.Message('CustomNotify', {'notify': 'You must be in space for this to work.'})
            return 
        for team in tg.teams:
            workingCopy = []
            for member in team:
                slim = bp.GetInvItem(member)
                if (slim is None):
                    continue
                workingCopy.append(self._TournamentWindow__GetValues(slim))

            workingCopy.sort(reverse=True)
            for entry in workingCopy:
                (primary, secondary, metaLevel, itemID,) = entry
                tg.SetTeamOrder(itemID, workingCopy.index(entry))
                slim = bp.GetInvItem(itemID)


        tg.ArrangeTargets()



    def __GetValues(self, slim):
        item = ()
        primaryField = self.sr.primarySortField.GetValue()
        prefs.SetValue('tournamentPriSort', primaryField)
        secondaryField = self.sr.secondarySortField.GetValue()
        prefs.SetValue('tournamentSecSort', secondaryField)
        for field in (primaryField, secondaryField):
            value = self._TournamentWindow__GetValue(slim, field)
            item += (value)

        item += (self._TournamentWindow__GetAttr(slim, const.attributeMetaLevel), slim.itemID)
        return item



    def __GetValue(self, slim, field):
        if (field in (const.attributeMass,
         const.attributeVolume,
         const.attributeRaceID)):
            lookup = {const.attributeMass: 'mass',
             const.attributeVolume: 'volume',
             const.attributeRaceID: 'raceID'}
            value = getattr(cfg.invtypes.Get(slim.typeID), lookup[field])
        elif (field in ('group',)):
            value = cfg.invtypes.Get(slim.typeID).Group().groupID
        elif (field in ('parent',)):
            dbrow = (sm.GetService('info').GetMetaTypesFromTypeID(slim.typeID) or [[0,
              slim.typeID,
              0]])
            value = dbrow[0][1]
        else:
            value = self._TournamentWindow__GetAttr(slim, field)
        return value



    def __GetAttr(self, slim, field):
        return sm.GetService('info').GetAttrDict(slim.typeID).get(field, 1.0)



    def DoLockGrid(self, *args):
        bp = sm.GetService('michelle').GetBallpark()
        for ballID in bp.balls.copy():
            if (ballID == bp.ego):
                continue
            item = bp.GetInvItem(ballID)
            if ((item is not None) and (item.categoryID == const.categoryShip)):
                if (item.itemID not in sm.GetService('target').GetTargets()):
                    filterValue = getattr(item, self.sr.filter.GetValue())
                    if (filterValue in (self.sr.teamAlpha.GetValue(), self.sr.teamBeta.GetValue())):
                        sm.GetService('target').LockTarget(item.itemID, autotargeting=True)




    def DoUnlockAll(self, *args):
        sm.GetService('target').ClearTargets()



    def DoWindowReload(self, *args):
        r = sm.GetService('window').GetWindow('tournament', create=0)
        if (r is not None):
            r.CloseX()
        r = sm.GetService('window').GetWindow('tournament', create=1)



    def DoHideWnd(self, *args):
        sm.GetService('window').GetWindow('tournament', create=0).state = uix.UI_HIDDEN



    def SwapTeams(self, *args):
        for itemID in sm.GetService('target').GetTargets():
            sm.GetService('target').ToggleTeam(itemID)





